document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    
    loginForm.addEventListener('submit', function(event) {
        event.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const role = document.querySelector('input[name="role"]:checked').value;
        
        // 发送请求到后端进行验证
        fetch('http://localhost:5000/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password,
                role: role === '学生' ? 'student' : 'delivery_person'
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('登录失败');
            }
            return response.json();
        })
        .then(data => {
            // 保存用户信息到localStorage
            localStorage.setItem('user', JSON.stringify({
                user_id: data.user_id,
                username: username,
                role: role
            }));
            
            // 根据角色跳转到不同的主页
            if (role === '学生') {
                window.location.href = 'student_home.html';
            } else {
                window.location.href = 'delivery_home.html';
            }
        })
        .catch(error => {
            alert('登录失败：' + error.message);
            console.error('登录错误：', error);
        });
    });
});